package com.example.opslog;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ThreadLocalRandom;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Service;

/**
 * @Author: Administrator
 * @Description:
 * @Date: Created in 2019-06-04 11:11
 * @Modified By:
 */
@Slf4j
@Service
@Lazy(false)
@EnableScheduling
public class StaffStatisticsListenSchedule1 implements SchedulingConfigurer {

  public String cron = "0/{} * * * * ?";


  int i = 0;

  @Override
  public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {

    taskRegistrar.addTriggerTask(new Runnable() {
      @Override
      public void run() {
        i++;
        // 需要实现的任务逻辑
        log.info("第{}次开始执行操作... 时间：【{}】", i, new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(new Date()));

      }
    }, new Trigger() {
      @Override
      public Date nextExecutionTime(TriggerContext triggerContext) {

        String number = ThreadLocalRandom.current().nextInt(10) + "";
        log.info("时间随机数：{}", number);

        String tempCron = cron.replaceAll("\\{\\}", number);

        log.info("出发时间表达式：{}", tempCron);
        //任务触发，修改任务的执行周期
        CronTrigger cronTrigger = new CronTrigger(tempCron);
        Date nextExecutionTime = cronTrigger.nextExecutionTime(triggerContext);

        return nextExecutionTime;
      }
    });

  }
}
